//
//  KDMonitorController.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/10/29.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "KDMonitorController.h"
#import "KDMonitorBodyView.h"
#import "SVProgressHUD.h"
#import "KDMBaseBoard.h"
#import "KDMBaseBoardModel.h"
#import "KDMBodyViewModel.h"
#import "KDMSettingController.h"
#import "KDMonitorRequestTool.h"
#import "KDBaesMonitorModel.h"
#import "KDBaseParam.h"
#import "KDMGetWebListResult.h"
#import "KDMGetWeiboListResult.h"
#import "KDMGetAuthorListResult.h"
#import "KDMGetKeyWordListResult.h"
#import "KDMGetAppListResult.h"
#import "KDReportController.h"
#import "KDMRelationController.h"
#import "KDPatrolgetReportParam.h"
#import "KDMListCellBaseModel.h"
#import "GBSingleWebViewController.h"
#import "KDGetMonitorListParam.h"
#import "KDSearchHomeController.h"
#import "KDStatusResult.h"

#import "KDMListCell.h"
#import "KDGetKeywordListParam.h"
#import "KDMGetWebListParam.h"
#import "KDGetAuthorListParam.h"
#import "KDGetWeiboListParam.h"
#import "KDWebEditCellModel.h"
#import "KDMGetWebListParam.h"
#import "KDGetAppListParam.h"
#import "KDMBaseBoard.h"
#import "KDMBaseBoardModel.h"
#import "GBAddFriendAnimation.h"
#import "KDMKeywordMonitorResult.h"
#import "findWebBloclListParam.h"
#import "findWebBloclListResult.h"
#import <MobileCoreServices/MobileCoreServices.h>
NSInteger const PAGE_NUMBER = 4;
#define BTN_WIDTH (screenW - 40 ) / PAGE_NUMBER
#define BTN_WIDTH1 screenW / PAGE_NUMBER //非平台版本的宽度
CGFloat const SETBTN_WIDTH = 36;

#define  HEADSCROLLH 44
NSInteger const BodyTag = 666;
CGFloat const RIGHTIMAGE_HEIGHT = 40;
CGFloat const Cell_H = 120;

@interface KDMonitorController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate, KDMListCellDelegate, KDMSettingControllerDelegate, KDMBaseboardDelegate>
/***  头部的scrollView*/
@property (weak, nonatomic) UIScrollView *headScrollView;

/** navBar右边的自定义按钮*/
@property (nonatomic, weak) UIButton *rightBarBtn;
/** navBar左边的自定义按钮*/
@property (nonatomic, weak) UIButton *leftBarBtn;
@property (nonatomic, weak) UIButton *selectDetailBtn;
/** 当前显示的tableView*/
@property (nonatomic, weak) UITableView *currentTabV;
/** 当前的baseBoardModel*/
@property (nonatomic, strong) KDMBaseBoardModel *baseBoardModel;
/** 默认的baseBoardModel*/
@property (nonatomic, strong) KDMBaseBoardModel * defaultBaseBoardModel;
/**
 * tableView的model的数据*
 */
@property (nonatomic, strong) NSDictionary *dataDic;
/**
 *  加载第几页
 */
@property (nonatomic, strong) NSString *page;


/***  BaseBoard那边传过来的模型 */
//@property (nonatomic, strong) KDMBaseBoardModel *baseBoardModel;



/***  被选中的主题btn*/
@property (nonatomic, weak) UIButton *selectBtn;

/***  头部scrollView下面那个最大的scrollView*/
@property (nonatomic, weak) UIScrollView *bodyScrollView;
/**
 *  当前的bodyView
 */
//@property (nonatomic, weak) KDMonitorBodyView *currentBodyView;
/**
 *  所有数据的集合
 */
@property (nonatomic, strong) NSArray * themeArr;
/**
 *  没有数据时的提示
 */
@property (nonatomic, weak) UIView * notice;
/** 右边弹出的选择界面*/
@property (nonatomic, weak) KDMBaseBoard *baseView;
/** 右边弹出的选择界面的遮盖*/
@property (nonatomic, weak) UIButton *cover;
@property (nonatomic, strong) NSDateFormatter *fmt;
/**
 *  所有的列表数据
 */
@property (nonatomic, strong) NSArray *infoArr;

/**
 *  版本
 */
@property (nonatomic, assign) NSInteger version;
/**
 *  地区类型
 */
@property (nonatomic, assign) NSInteger regionType;
/**
 *  当前属于第几个
 */
@property (nonatomic, copy) NSString *currentIndex;
/**
 *  所有网站子板块的存放地
 */
@property (nonatomic, strong) NSMutableDictionary *webBlockDic;

@end

@implementation KDMonitorController
@synthesize  baseBoardModel = _baseBoardModel;

#pragma mark - 懒加载区
- (NSDateFormatter *)fmt
{
    if (!_fmt) {
        _fmt = [[NSDateFormatter alloc]init];
        _fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];;
        _fmt.dateFormat = @"yyyy-MM-dd";
    }
    return _fmt;
}
- (NSMutableDictionary *)webBlockDic{
    if (!_webBlockDic) {
        _webBlockDic = [NSMutableDictionary dictionary];
    }
    return _webBlockDic;
}
- (NSArray *)themeArr
{
    if (!_themeArr) {
        _themeArr = [NSArray new];
    }
    return _themeArr;
}
- (NSString *)page
{
    if (!_page) {
        _page = @"1";
    }
    return _page;
}
- (NSArray *)infoArr
{
    if (!_infoArr) {
        _infoArr = [NSArray new];
    }
    return _infoArr;
}
- (NSDictionary *)dataDic
{
    if (!_dataDic) {
        _dataDic = [NSDictionary dictionary];
    }
    return _dataDic;
}
- (KDMBaseBoardModel *)baseBoardModel
{
    if (!_baseBoardModel) {//那里找不到了，就自己建
        _baseBoardModel = [[KDMBaseBoardModel alloc]init];
        _baseBoardModel.webSrcType = @"0";
        //        NSDate *newdate = [[NSDate date] initWithTimeInterval:- (24 *60 * 60 * 6 )sinceDate:[NSDate date]];
        _baseBoardModel.startTime = @"1970-01-01";//[self.fmt stringFromDate:newdate];
        _baseBoardModel.endTime = @"";
        _baseBoardModel.timeIndex = @"9";
        _baseBoardModel.docType = @"0";
        _baseBoardModel.bussiness = @"0";
        if (self.mainType == 3 || self.mainType == 1) {
            if (self.regionType == 0) {
                _baseBoardModel.regionType = 4;
            }else{
                _baseBoardModel.regionType = self.regionType;
            }
        }
        self.defaultBaseBoardModel = _baseBoardModel ;
    }
    return _baseBoardModel;
}
#pragma mark - 板块设置区
//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    //只在本控制器隐藏
//    self.navigationController.navigationBar.hidden = YES;
//    
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpNavBar];
    
    KDAccount *account = [KDAccountTool account];
    self.version = account.version;
    [self setUpHeadScrollView];
    [self loadData];
    self.currentIndex = @"0";

    // Do any additional setup after loading the view.
}
- (void)setUpNavBar{
//    self.title = @"关键词监测";
    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"leftArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(backViewClick)];
    
    [self setUpRightBarBtn];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightBarBtn];;
}
/***  创建右边筛选按钮 */
- (void)setUpRightBarBtn
{
    UIButton *rightBarBtn = [[UIButton alloc]init];
    self.rightBarBtn = rightBarBtn;
    UIImage *image = [UIImage imageNamed:@"筛选"];
    rightBarBtn.width = image.size.width ;
    rightBarBtn.height = image.size.height;
    rightBarBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightBarBtn setImage:image forState:UIControlStateNormal];;
    [rightBarBtn addTarget:self action:@selector(rightBarBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBarBtn];;
    
}
- (void)setUpHeadScrollView{
    //加一个挡板
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:view];
    //初始化headScrollView
    UIScrollView *headScrollView = [[UIScrollView alloc]init];
    self.headScrollView = headScrollView;
    headScrollView.frame = CGRectMake(0, 0, screenW, HEADSCROLLH);
    headScrollView.backgroundColor = [UIColor whiteColor];
    headScrollView.showsHorizontalScrollIndicator = NO;
    headScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.headScrollView];
    //添加各主题子控件
//    [self setUpHeadBtn];
//    [self setUpBodyScrollView];
}
- (void)setUpHeadBtn
{
//    if (!self.version) {
//        [self setUpRightBarBtn];
//    }
//    _headScrollView.contentSize = CGSizeMake(BTN_WIDTH * self.infoArr.count, HEADSCROLLH);
    CGFloat lastW = 0.0;//上一个btn的宽度
    for (int i = 0; i < self.themeArr.count; i++) {
        KDBaesMonitorModel *model = self.themeArr[i];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        if (i == 0) {
            btn.x = 10;
        }else{
            
            btn.x = lastW +10;
            
        }
        CGRect labelRect = [model.m_Name boundingRectWithSize:CGSizeMake(screenW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
        //        KDLog(@"%@",NSStringFromCGRect(labelRect));
        if (self.themeArr.count <= 1) {//如果小于4个，就平分
            btn.width = (screenW - SETBTN_WIDTH)/(self.themeArr.count *1.0);
        }else{
            btn.width = labelRect.size.width +10;
        }
       
        btn.height = self.headScrollView.height -10;
        
        btn.y = 5;
        btn.tag = 100+i;
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        UIImage *image2 = [UIImage imageNamed:@"btn_background"];
        CGFloat top = 0; // 顶端盖高度
        CGFloat bottom = 0 ; // 底端盖高度
        CGFloat left = 15; // 左端盖宽度
        CGFloat right = 15; // 右端盖宽度
        UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
        image2 = [image2 resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
        [btn setBackgroundImage:image2 forState:UIControlStateNormal];
        //
        [btn setBackgroundImage:image2 forState:UIControlStateSelected];
        btn.titleLabel.layer.cornerRadius = 5;
        btn.titleLabel.clipsToBounds = YES;
        [btn setTitle:model.m_Name forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(detailBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitleColor: WQColor(149, 149, 149) forState:UIControlStateNormal];
        [btn setTitleColor:WQColor(85, 196, 95) forState:UIControlStateSelected];
        //        btn.backgroundColor = WQColor(249, 249, 249);
        //        btn.tintColor = KDColor;
        if (btn.tag == 100) {
            self.selectDetailBtn = btn;
        }
        [self.headScrollView addSubview:btn];
         lastW = CGRectGetMaxX(btn.frame);
        KDLog(@"%f",CGRectGetMaxX(btn.frame));
    }
    self.headScrollView.contentSize = CGSizeMake(lastW, 1);
    KDLog(@"%@", NSStringFromCGSize(self.headScrollView.contentSize));

//    _bodyScrollView.contentSize = CGSizeMake(screenW * self.themeArr.count, 1);
}
- (void)setSelectDetailBtn:(UIButton *)selectDetailBtn
{
    _selectDetailBtn.selected = NO;
    _selectDetailBtn = selectDetailBtn;
    _selectDetailBtn.selected = YES;
}
/***  创建装tableView的scrollView */
- (void)setUpBodyScrollView
{
    if (!self.bodyScrollView) {
        UIScrollView * bodyScrollView = [[UIScrollView alloc]init];
        self.bodyScrollView = bodyScrollView;
        bodyScrollView.frame = CGRectMake(0, CGRectGetMaxY(self.headScrollView.frame), screenW, screenH - CGRectGetMaxY(self.headScrollView.frame));
        bodyScrollView.delegate = self;
        
        bodyScrollView.showsHorizontalScrollIndicator = YES;
        bodyScrollView.pagingEnabled = YES;
        bodyScrollView.scrollEnabled = YES;
        bodyScrollView.contentSize = CGSizeMake(screenW * self.themeArr.count, 1);
        //        bodyScrollView.showsVerticalScrollIndicator = YES;
        [self.view addSubview:bodyScrollView];
        //初始化主题
        [self setUpTableView];
        
    }
}
/***  各大主题tableView的设置*/
- (void)setUpTableView
{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , 0, screenW, self.bodyScrollView.height  - 64) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    tableView.rowHeight = Cell_H;
    if (!iOS7) {
        tableView.estimatedRowHeight = Cell_H;
    }
    self.currentTabV = tableView;
    [self.bodyScrollView addSubview:tableView];
    tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadDetailData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreDetailData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    // 设置footer
    self.currentTabV.footer = footer;
    [self.currentTabV.header beginRefreshing];
}
///**
// *  设置bodyView的排列
// */
//- (void)setUpheadScrollView
//{
//    if (!self.currentBodyView) {
//        KDMonitorBodyView *body = [KDMonitorBodyView bodyViewWithFrame:CGRectMake(self.mainType.integerValue * screenW, 0, screenW, self.bodyScrollView.height)];
//        body.delegate = self;
////        KDMBodyViewModel *model = [[KDMBodyViewModel alloc]init];//fake data
////        model.mainType = self.mainType.integerValue;
//        body.tag = BodyTag + self.mainType.integerValue;
//        //    KDLog(@"%ld", body.tag);
//        [self.bodyScrollView addSubview:body];
//        self.currentBodyView = body;
//    }else if (!self.currentBodyView.model.infoArr){//还是获取不到第二层的数据,就先把按钮露出来再说
//        KDMBodyViewModel *model = [[KDMBodyViewModel alloc]init];
//        model.infoArr = nil;
//        model.mainType = self.mainType.integerValue;
//        model.version = self.version;
//        self.currentBodyView.model = model;
//    }
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"KDMonitorControllerTopicBtnDidClickNotyfication" object:nil userInfo:@{@"currentBodyView":self.currentBodyView}];
//}
/***  设置selectBtn的*/
- (void)setSelectBtn:(UIButton *)selectBtn
{
    _selectBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    _selectBtn = selectBtn;
    _selectBtn.selected = YES;
    [UIView animateWithDuration:1.0f animations:^{
        _selectBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    }];
}

/***  设置右边选择页面*/
-(void)setUpRightChoosePage
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (!self.cover) {
        //加蒙板
        UIButton *cover = [[UIButton alloc]initWithFrame:window.bounds];
        self.cover = cover;
        cover.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        
        [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
        [window addSubview:_cover];
    }
    self.cover.frame = window.bounds;
    //创建底板
    if (!self.baseView) {
        KDMBaseBoard *baseView = [KDMBaseBoard baseboard];
        self.baseView = baseView;
        baseView.delegate = self;
        baseView.x = screenW;
        baseView.y = 64;
        baseView.height = screenH - baseView.y ;
        baseView.width = screenW - screenW*0.175;
        baseView.mainPageType = self.mainType;
        
        [_cover addSubview:baseView];
    }
    KDBaesMonitorModel *model;
    if (self.themeArr.count) {
        model = self.themeArr[self.currentIndex.integerValue];
        _baseView.webBlockList = [self.webBlockDic objectForKey:model.m_Id];
    }
//    KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];

    _baseView.showReginType = self.regionType;
    _baseView.height = screenH - _baseView.y ;
    _baseView.width = screenW - screenW*0.175;
    [UIView animateWithDuration:0.4 animations:^{
        _baseView.x = screenW*0.175;
    }];
}
/**
 *  网络出错的提示view
 */
- (void)setUpNotise{
    if (self.notice) {
        [self.notice removeFromSuperview];
    }

    UIView * notice = [[UIView alloc]initWithFrame:CGRectMake(0, 34, screenW, screenH - CGRectGetMaxY(self.headScrollView.frame))];
    
    self.notice = notice;
    UIButton * noticeLb = [[UIButton alloc]init];
    noticeLb.frame = notice.bounds;
    notice.backgroundColor = BackGroundColor;
    [noticeLb setTitle:@"请点击屏幕，重新加载！" forState:UIControlStateNormal];
    [noticeLb setTitleColor:WQColor(178, 182, 184) forState:UIControlStateNormal];
    [noticeLb addTarget:self action:@selector(loadData) forControlEvents:UIControlEventTouchUpInside];
    [notice addSubview:noticeLb];
    [self.view addSubview:notice];
}
/**
 *  没有满足条件的数据的提示View
 */
- (void)setUpNoMoreNotise{
    UIView * notice = [[UIView alloc]initWithFrame:self.currentTabV.bounds];
    self.notice = notice;
    UILabel * noticeLb = [[UILabel alloc]initWithFrame:self.notice.bounds];
    notice.backgroundColor = BackGroundColor;
    notice.y = 0;
    noticeLb.centerY = noticeLb.height * 0.5;
    //    KDLog(@"%@", NSStringFromCGRect(notice.frame));
    noticeLb.text = @"暂时没有满足条件的数据";
    noticeLb.textColor = WQColor(178, 182, 184);
    noticeLb.textAlignment = NSTextAlignmentCenter;
    [notice addSubview:noticeLb];
    self.currentTabV.tableHeaderView = notice;
}
#pragma mark - 事件点击区

/***  顶部主题Btn被点击 */
-(void)detailBtnDidClick:(UIButton *)btn
{
    NSInteger num = btn.tag -100;
    [self.bodyScrollView setContentOffset:CGPointMake(screenW*num, self.bodyScrollView.contentOffset.y) animated:YES];
    [self.bodyScrollView scrollRectToVisible:CGRectMake(screenW * num, self.bodyScrollView.frame.origin.y, screenW, self.bodyScrollView.frame.size.height) animated:YES];
//    //被点击的btn的后一个btn
//    UIButton *btn1 = (UIButton *)[self.headScrollView viewWithTag:num +101];
//    UIButton *btn2 = (UIButton *)[self.headScrollView viewWithTag:num +99];
//    
//    NSInteger i = self.selectDetailBtn.tag - btn.tag;
//    float xx;
//    if (i > 0) {//向左点
//        xx = btn.x - btn2.width ;
//    }else{//向右点
//        xx = btn.x +btn1.width ;
//    }
//    self.selectDetailBtn.selected = NO;
    self.selectDetailBtn = btn;
    [self setUpTitleCenter:btn];
    
    //    KDLog(@"%f",xx);
//    [self.headScrollView scrollRectToVisible:CGRectMake(xx, self.headScrollView.y, btn.width, self.headScrollView.height) animated:YES];
}

/***  去掉蒙板及右边页 */
- (void)coverClick:(UIButton *)cover
{
    [UIView animateWithDuration:0.4 animations:^{
        self.baseView.x = screenW;
        
    } completion:^(BOOL finished) {
        
        self.cover.frame = CGRectMake(0, 0, 0, 0);
        //        self.rightBarBtn.selected = NO;
        
    }];
    
}

- (void)backViewClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}

/***  添加蒙板并显示右边页 */
- (void)rightBarBtnClick:(UIButton *)rightBarBtn
{
    if (!rightBarBtn.selected) {
        
        //设置右边的选择页面
        [self setUpRightChoosePage];
    } else
    {
        [self coverClick:self.cover];
    }
    rightBarBtn.selected = rightBarBtn.selected;
    
}

#pragma mark - 网络加载区
- (void)loadData{
    [self.notice removeFromSuperview];
    WS(ws);
    KDBaseParam *param = [[KDBaseParam alloc]init];
    switch (self.mainType) {
        case 0:
            param.method = @"getMonitorKeywordList";
            break;
        case 1:
            param.method = @"getMonitorWebSiteList";
            break;
        case 2:
            param.method = @"getMonitorAuthorList";
            break;
        case 3:
            param.method = @"getMonitorAppList";
            break;
        default:
            break;
    }
    [KDMonitorRequestTool getWithParam:param WithMainType:self.mainType success:^(KDStatusResult * responseObejct) {//正常情况下，就加载数据
//        NSMutableDictionary *tempDic = [NSMutableDictionary new];
        if ([responseObejct.status isEqualToString:@"notlogin"]) {
            //写提示“该账号已在别处登录”
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
        }{
//            KDMBodyViewModel *model = [[KDMBodyViewModel alloc]init];
            switch (ws.mainType) {
                case 0:{
                    KDMGetKeyWordListResult *result = (KDMGetKeyWordListResult *)responseObejct;
                    ws.themeArr =  result.info;
                    break;
                }
                case 1:{
                    KDMGetWebListResult *result = (KDMGetWebListResult *)responseObejct;
                    ws.themeArr =  result.info;
                    self.regionType = result.regionType;
                    [ws addAllBtn];
                    break;
                }
                case 2:{
                    KDMGetAuthorListResult *result = (KDMGetAuthorListResult *)responseObejct;
                    ws.themeArr =  result.info;
                    break;
                }
                case 3:{
                    KDMGetAppListResult *result = (KDMGetAppListResult *)responseObejct;
                    ws.themeArr =  result.info;
                    self.regionType = result.regionType;
                    [ws addAllBtn];
                    break;
                }
                default:
                    break;
            }
            
            [self setUpHeadBtn];
            [self setUpBodyScrollView];
        }
        
    } failure:^(NSError *error) {
        KDLog(@"%@",error);
        [ws setUpNotise];
    }];
}
- (void)addAllBtn{
    //手动添加一个全部
    KDBaesMonitorModel *model = [[KDBaesMonitorModel alloc]init];
    //            model.m_Id = nil;
    model.m_Name = @" 全部 ";
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.themeArr];
    [arr insertObject:model atIndex:0];
    
    self.themeArr = arr;
}
- (KDGetMonitorListParam *)requestMethod{
    KDGetMonitorListParam *param1;
    if (!self.themeArr.count) {//没有二级菜单，返回无数据
        [self setUpNoMoreNotise];
        return nil;
    }
    //创建参数
    switch (self.mainType) {//
        case 0:{
            KDGetKeywordListParam *param = [[KDGetKeywordListParam alloc]init];
            param.method = @"getMonitorKeywordItemList";
            param.p = self.page;
            param.limit = @"20";
            param.kindType = self.baseBoardModel.webSrcType;
            param.startTime = self.baseBoardModel.startTime;
            param.endTime = self.baseBoardModel.endTime;
            param.property = self.baseBoardModel.docType;
            param.sortType = @"0";
            param.keyword = self.baseBoardModel.secondSearch;
            
            KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
            param.m_Id =  model.m_Id ;
            param1 = param;
            break;
        }
        case 1:{
            
            KDMGetWebListParam *param = [[KDMGetWebListParam alloc]init];
            param.method = @"getMonitorWebSiteItemList";
            param.p = self.page;
            param.business = (self.baseBoardModel.bussiness.integerValue)?@"true":@"false";
            param.keyword = self.baseBoardModel.secondSearch;
            param.startTime = self.baseBoardModel.startTime;
            param.endTime = self.baseBoardModel.endTime;
            param.property = self.baseBoardModel.docType;//
            param.limit = @"20";
            param.pageId = self.baseBoardModel.pageId;
            param.regionType = self.baseBoardModel.regionType;
            KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
            param.wsm_id = model.m_Id ;
            param1 = param;
            break;
        }
        case 2:{
            KDGetAuthorListParam *param = [[KDGetAuthorListParam alloc]init];
            param.method = @"getMonitorAuthorItemList";
            param.startTime = self.baseBoardModel.startTime;
            param.endTime = self.baseBoardModel.endTime;
            param.property = self.baseBoardModel.docType;
            param.p = self.page;
            param.limit = @"20";
            param.keyword = self.baseBoardModel.secondSearch;
            param.kindType = self.baseBoardModel.webSrcType;
            param.sortType = @"0";
            KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
            param.a_id =  model.m_Id;
            param1 = param;
            break;
        }
        case 3:{
            KDGetAppListParam *param = [[KDGetAppListParam alloc]init];
            param.method = @"getMonitorAppItemList";
            param.p = self.page;
            param.limit = @"20";
            param.startTime = self.baseBoardModel.startTime;
            param.endTime = self.baseBoardModel.endTime;
            //            param.property = self.baseBoardModel.docType;
            param.business = (self.baseBoardModel.bussiness.integerValue)?@"true":@"false";//待定
            param.keyword = self.baseBoardModel.secondSearch;
            param.property = self.baseBoardModel.docType;
            param.sortType = @"0";
            param.regionType = self.baseBoardModel.regionType;
            KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
            param.app_id = model.m_Id ;
            param1 = param;
            break;
        }
        default:
            break;
    }
    return param1;
}
- (void)loadDetailData{
    if (self.notice) {
        [self.notice removeFromSuperview];
    }
    
    self.currentTabV.tableHeaderView.height = 0;
    self.page = @"1";
    KDGetMonitorListParam *param = [self requestMethod];
    if (!param) {//如果没有子主题了就不要再请求了
        [self.currentTabV.header endRefreshing];
        return;
    }
    WS(ws);
    [KDMonitorRequestTool getMonitorListWithParam:param WithMainType:self.mainType success:^(KDMKeywordMonitorResult * responseObejct) {
        KDMKeywordMonitorResult *result = responseObejct;
        if ([result.status isEqualToString:@"notlogin"]) {//如果被别人强制登陆了
            //写提示“该账号已在别处登录”
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:ws cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [ws.currentTabV.header endRefreshing];
            
        }else{//正常情况下，就加载数据
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            if (!result.info) {
                [ws setUpNoMoreNotise];
                [ws.currentTabV.header endRefreshing];
                return ;
            }
            if (!ws) {
                return;
            }
            [dic setObject:result.info forKey:ws.currentIndex];
            ws.dataDic = dic;
            ws.infoArr = result.info;
            if (ws.infoArr.count == 0) {
                [ws setUpNoMoreNotise];
            }
            //设置page＝1，方便上拉加载时重新从第一页开始加载,
            
            ws.page = [NSString stringWithFormat:@"%ld",ws.page.integerValue +1];
            [ws.currentTabV reloadData];
            [ws.currentTabV.header endRefreshing];
            [ws.currentTabV.footer resetNoMoreData];
        }
        KDLog(@"%@", result.info);
    } failure:^(NSError *error) {
        [ws.currentTabV.header endRefreshing];
        KDLog(@"%@",error);
        UIAlertView *messageView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败，请检查网络" delegate:ws cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [messageView show];
    }];
}
- (void)loadMoreDetailData{
    [self requestMethod];
    KDGetMonitorListParam *param = [self requestMethod];
    WS(ws);
    [KDMonitorRequestTool getMonitorListWithParam:param WithMainType:self.mainType success:^(KDMKeywordMonitorResult *responseObejct) {
        KDMKeywordMonitorResult *result = responseObejct;
        if ([result.status isEqualToString:@"notlogin"]) {//如果被别人强制登陆了
            //写提示“该账号已在别处登录”
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [ws.currentTabV.header endRefreshing];
            
        }else{//正常情况下，就加载数据
            if (responseObejct.count <= ws.infoArr.count) {
                [ws.currentTabV.footer endRefreshing];
                return ;
            }
            NSMutableArray *arr = [NSMutableArray arrayWithArray:ws.infoArr];
            [arr addObjectsFromArray: result.info];
            ws.infoArr = arr;
            [ws.currentTabV reloadData];
            [ws.currentTabV.footer endRefreshing];
            if (responseObejct.count <= ws.infoArr.count) {
                [ws.currentTabV.footer endRefreshing];
            }
            //设置page++,
            ws.page = [NSString stringWithFormat:@"%ld",ws.page.integerValue +1];
            [ws.currentTabV reloadData];
            [ws.currentTabV.footer endRefreshing];
            //            KDLog(@"%@", result.info);
        }
    } failure:^(NSError *error) {
        [ws.currentTabV.footer endRefreshing];
        KDLog(@"%@",error);
        UIAlertView *messageView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败，请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [messageView show];
    }];
}
/**
 *  获取某网站所有子板块的请求
 */
- (void)getWebBlockListRequest{
    WS(ws);
//    self.page = @"1";
    findWebBloclListParam *param = [[findWebBloclListParam alloc]init];
    param.method = @"getMonitorWebPageList";
    KDBaesMonitorModel *model = self.themeArr[self.currentIndex.integerValue];
    param.wsm_id = model.m_Id ;
    [KDMonitorRequestTool findWebBlocklListMonitorWithParam:param success:^(findWebBloclListResult *responseObejct) {
        //        KDLog(@"%@", responseObejct);
        if ([responseObejct.status isEqualToString:@"ok"]) {
            NSArray *info ;
            if (!responseObejct.webPageInfoList) {//如果没有子集了，就创建一个空的
                info = [NSArray array];
            }else{
                NSMutableArray *mutableArr = [NSMutableArray arrayWithArray:responseObejct.webPageInfoList];
                KDWebEditCellModel *model = [[KDWebEditCellModel alloc]init];
                model.w_Name = @"全部";
                [mutableArr insertObject:model atIndex:0];
//                model.
                info = mutableArr;
            }
            
            [ws.webBlockDic setObject:info forKey:model.m_Id];
        }
    } failure:^(NSError *error) {
        KDLog(@"%@", error);
    }];
}
#pragma mark - UIScrollViewDelegate
//scrollView滑动停止会调动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.bodyScrollView)
    {
        int num = (int)scrollView.contentOffset.x/screenW;
        UIButton *btn = (UIButton *)[self.headScrollView viewWithTag:num +100];
        [self adjustFrameWithScrollView:scrollView];
        self.selectDetailBtn = btn;
        [self setUpTitleCenter:btn];
    }
}
/**
 *  将被点击的按钮设置到中间
 */
- (void)setUpTitleCenter:(UIButton *)centerBtn{
    CGFloat offsetX = centerBtn.centerX - screenW *0.5;
    if (offsetX < 0) offsetX = 0;
    
    //获取最大滚动范围
    CGFloat maxOffsetX = self.headScrollView.contentSize.width - screenW;
    if (offsetX > maxOffsetX) offsetX = maxOffsetX;
    // 滚动标题滚动条
    [self.headScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}
/***  当scrollView自动停止的时候会调用（不包括手抓的）*/
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if (scrollView == self.bodyScrollView)
    {
        [self adjustFrameWithScrollView:scrollView];
    }
}

/***  重新确认CurrentTableView */
- (void)adjustFrameWithScrollView:(UIScrollView *)scrollView
{
    //    WS(ws);
    //防止没刷完之前就切换后一直刷的bug
    [self.currentTabV.header endRefreshing];
    NSUInteger num = (NSUInteger)scrollView.contentOffset.x/screenW;
    
    self.currentIndex = [NSString stringWithFormat:@"%ld", num];
    self.currentTabV = (UITableView *)[self.bodyScrollView viewWithTag:1000+num];
    //    self.homeThemeModel = self.themeArr[num];
    if (!self.currentTabV) { //划到这页，判断这页有无tableView，没有的话就建一个
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(screenW *num , 0, screenW, self.bodyScrollView.height - 64) style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tag = num + 1000;
        tableView.tableFooterView = [UIView new];
        tableView.backgroundColor = BackGroundColor;
        tableView.separatorColor = BackGroundColor;
        tableView.rowHeight = Cell_H;
        if (!iOS7) {
            tableView.estimatedRowHeight = Cell_H;
        }
        [self.bodyScrollView addSubview:tableView];
        tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadDetailData)];
        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreDetailData)];
        [footer setTitle:@"" forState:MJRefreshStateIdle];
        tableView.footer = footer;
        self.currentTabV = tableView;
        if (self.mainType == 1) {//如果是网站监测的话就加载子板块列表
            [self getWebBlockListRequest];
        }
    }
    self.baseBoardModel = self.defaultBaseBoardModel;
    [self.currentTabV.header beginRefreshing];
    
    self.infoArr = self.dataDic[self.currentIndex];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KDMListCell *cell = [KDMListCell cellWithTableView:tableView andVersion:self.version];
    //    KDLog(@"waimian%d", indexPath.row);
    cell.delegate = self;
    if (tableView == self.currentTabV)
    {
        cell.delegate = self;
        if (self.infoArr.count != 0)
        {
            cell.model = self.infoArr[indexPath.row];
        }
        return cell;
    }else{
        return cell;
    }
}
/**
 *  cell被点击了
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.currentTabV) {
            if (self.infoArr.count == 0) {
                return;
            }
        KDMListCell *cell = (KDMListCell *)[tableView cellForRowAtIndexPath:indexPath];
        cell.highlight = YES;
        NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
        [arr replaceObjectAtIndex:indexPath.row withObject:cell.model];
        self.infoArr = arr;
        KDMListCellBaseModel *model = self.infoArr[indexPath.row];
        GBSingleWebViewController *singleCtrl = [[GBSingleWebViewController alloc]init];
        singleCtrl.docid = model.docId;
        singleCtrl.titleee = model.title;
        singleCtrl.isCollect = model.isSave;
        singleCtrl.keyword = model.keywords;
        singleCtrl.whichPage = [NSString stringWithFormat:@"%ld",(long)indexPath.row] ;
        singleCtrl.url = model.url;
        singleCtrl.comeFrom = @"4";
        singleCtrl.report = model.isReport;
        singleCtrl.ori_content = model.content;
        singleCtrl.st = model.date;
        singleCtrl.ori_author = model.author;
        singleCtrl.ori_webname = model.source;
        
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:singleCtrl animated:YES];
        self.hidesBottomBarWhenPushed = NO;

    }
}



#pragma mark - KDMListCellDelegate
/**
 *  上报按钮被点击了
 */
- (void)KDMListCell:(KDMListCell *)cell reportBtnClick:(UIButton *)reportBtn{
    KDMListCellBaseModel *model = cell.model;
    KDReportController *reportCtrl = [[KDReportController alloc]init];
    KDPatrolgetReportParam *param = [[KDPatrolgetReportParam alloc]init];
    param.ori_url = model.url;
    param.ori_title = model.title;
    param.ori_content = model.content;
    param.st = model.date;
    param.doc_id = model.docId;
    if (model.author.length == 0) {
        param.ori_author = @"";
    }else{
        param.ori_author = model.author;
    }
    param.ori_webname = model.source;
    reportCtrl.param = param;
    reportCtrl.type = 0;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:reportCtrl animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
/**
 *  相关按钮被点击了
 */
- (void)KDMListCell:(KDMListCell *)cell relationBtnClick:(UIButton *)relationBtn{
    KDMListCellBaseModel *model = cell.model;
    KDMRelationController *relation = [[KDMRelationController alloc]init];
    KDGetMonitorListParam *param = [[KDGetMonitorListParam alloc]init];
    param.topicId = model.topicId;
    relation.param = param;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:relation animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)KDMListCell:(KDMListCell *)cell collectBtnClick:(UIButton *)collectBtn{
    NSIndexPath *ip = [self.currentTabV indexPathForCell:cell];
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
    [arr replaceObjectAtIndex:ip.row withObject:cell.model];
    self.infoArr = arr;
}


#pragma mark - KDMonitorBodyViewDelegate

/**
 *  账号在别处登陆
 *
 */
- (void)bodyViewDidLoginedByOther:(KDMonitorBodyView *)bodyView{
    [self presentViewController:[[KDNewfeatureController alloc]init] animated:YES completion:nil];
}
/**
 *  设置按钮被点击了
 */
- (void)KDMonitorBodyView:(KDMonitorBodyView *)bodyView SetBtnClickWithKDMBodyViewModel:(KDMBodyViewModel *)model{
    KDMSettingController *setVc = [[KDMSettingController alloc]init];
    setVc.delegate = self;
    setVc.mainType = model.mainType;
//    self.navigationController.navigationBar.hidden = NO;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:setVc animated:YES];
    self.hidesBottomBarWhenPushed = NO;

}


#pragma mark - KDMSettingControllerDelegate
- (void)KDMSettingController:(KDMSettingController *)settingCtr backBtnClickWithMainType:(NSInteger)mainType{
    [self loadData];
}


#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView.title isEqualToString:@"该账号已在别处登录"]) {
        switch (buttonIndex) {
            case 0:
                [self presentViewController:[[KDNewfeatureController alloc]init] animated:YES completion:nil];
                break;
            default:
                break;
        }
    }
    
}
#pragma  mark - KDMBaseboardDelegate
/**
 *  确定按钮被点击了
 */
- (void)baseBoard:(KDMBaseBoard *)baseBoard
confirmBtnDidClickWithBaseBoardModel:(KDMBaseBoardModel *)model{
    self.baseBoardModel = model;
    [self.currentTabV.header beginRefreshing];
    [self coverClick:self.cover];
}
@end
